package com.qf.interceptor;

import com.qf.bean.Permission;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
 * projectName: 2103--RBAC
 *
 * @author: MaTianWei
 * time: 2021/7/9 22:23
 * description:
 */

public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取访问资源
        // http://localhost:8080  =   /class/test  = uri
        String uri = request.getRequestURI();
        //2.匿名资源判断
        ServletContext application = request.getServletContext();
        //获取匿名资源清单
        Properties anonymity = (Properties) application.getAttribute("anonymity");
        //判断访问的资源是否是匿名资源
        if (anonymity.containsValue(uri)) {
            //放行
            return true;
        }
        //3.认证资源判断
        //获取是否登录
        Map map = (Map) request.getSession().getAttribute("ret");
        if (map == null) {
            //未认证提示
            request.getRequestDispatcher("/user/noauthentication").forward(request,response);
            return false;
        }
        //获取认证路径
        Properties authentication = (Properties) application.getAttribute("authentication");
        if (authentication.containsValue(uri)) {
            return true;
        }
        //4.授权资源判断
        List<Permission> permissionList = (List<Permission>) map.get("permission");

        int flag = 0; //未授权
        for (Permission permission : permissionList) {

            if (permission.getpUrl().equalsIgnoreCase(uri)) {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
        {
            request.getRequestDispatcher("/user/noauthorization").forward(request,response);
            //没有授权
            return false;
        }
        return true;
    }
}